﻿using System;
using System.IO.Ports;
using System.Windows.Forms;
using NetworkSerialPort.Helper;
using oModbus.Message;

namespace NetworkSerialPort
{
    public partial class ClientForm : Form
    {
        public ClientForm()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBoxSerialPorts.Items.Clear();
            foreach (var port in SerialPort.GetPortNames())
            {
                comboBoxSerialPorts.Items.Add(port);
            }
            if (comboBoxSerialPorts.Items.Count > 0)
                comboBoxSerialPorts.SelectedIndex = 0;
            comboBoxParity.Items.Clear();
            comboBoxParity.Items.Add(Parity.None.ToString());
            comboBoxParity.Items.Add(Parity.Odd.ToString());
            comboBoxParity.Items.Add(Parity.Even.ToString());
            comboBoxParity.Items.Add(Parity.Mark.ToString());
            comboBoxParity.Items.Add(Parity.Space.ToString());
            comboBoxParity.SelectedIndex = 0;
            comboBoxDataBits.SelectedIndex = 0;
            comboBoxStopBits.SelectedIndex = 0;
            //BtnConnect.Enabled = true;
            //BtnDisconnect.Enabled = false;
            comboBoxBaudRate.SelectedIndex = 1;
            txtPort.Text = ConfigureAppConfig.GetConnectionStringsValue("Port");
            ip_txt.Text = ConfigureAppConfig.GetConnectionStringsValue("Ip");
        }

        private NetworkSerialClient _client;
        private void btn_Inti_Click(object sender, EventArgs e)
        {
            int portint;
            if (!int.TryParse(txtPort.Text, out portint))
            {
                MessageBox.Show(@"输入值不是合法的数字", @"错误");
                return;
            }
            var log = new LogInfo("log4net.config", "");
            if (comboBoxBaudRate.Text.Length > 0)
            {


                SerialPort serialPort = new SerialPort(comboBoxSerialPorts.Text)
                {
                    BaudRate = Convert.ToInt32(comboBoxBaudRate.Text),
                    DataBits = 8,
                    Parity = Parity.None,
                    StopBits = StopBits.One
                };
                switch (comboBoxStopBits.Text)
                {
                    case "None":
                        serialPort.StopBits = StopBits.None;
                        break;
                    case "1":
                        serialPort.StopBits = StopBits.One;
                        break;
                    case "1.5":
                        serialPort.StopBits = StopBits.OnePointFive;
                        break;
                    case "2":
                        serialPort.StopBits = StopBits.Two;
                        break;

                }

                _client = new NetworkSerialClient(ip_txt.Text, portint, serialPort, log);
                _client.LogEvent += _communServer_LogEvent;
                var state = _client.Connection();
                if (state == NetworkSerialClienInit.Success)
                {
                    btn_Inti.Enabled = false;
                    btnStop.Enabled = true;
                    btnSend.Enabled = true;
                }
                else if (state == NetworkSerialClienInit.NetworFail)
                {
                    MessageBox.Show(@"打开失败，网络打开失败");
                }
                else if (state == NetworkSerialClienInit.SerialFail)
                {
                    MessageBox.Show(@"打开失败，串口打开失败");
                }
                else
                {
                    MessageBox.Show(@"打开失败，其它");
                }
            }
            else
            {
                MessageBox.Show(@"打开失败，本机没有串口");
            }
            //var dd = new LogInfo("log4net.config", "");
        }
        private void _communServer_LogEvent(string title, string data)
        {
            if (ckbShow.Checked)
            {

                if (txtInfo.InvokeRequired)
                {
                    //后端线程向主线程记日志
                    Invoke(new Action<string, string>(_communServer_LogEvent), title, data);
                }
                else
                {
                    //主线程直接记日志

                    if (ckbHex.Checked)
                    {
                        //txtInfo.Text += title + data.GetHexString()+ Environment.NewLine;
                        txtInfo.Text += title + data + Environment.NewLine;
                    }
                    else
                    {
                        // txtInfo.Text += title + data.GetHexString() + Environment.NewLine;
                        txtInfo.Text += title + data + Environment.NewLine;
                    }
                }

            }

        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            _client.Close();
            btn_Inti.Enabled = true;
            btnStop.Enabled = false;
            btnSend.Enabled = false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            ushort startAddress = 100;
            ushort number = 5;

            ReadCoilRequest request = new ReadCoilRequest(1, startAddress, number);
            byte[] data = request.PackingMessage();
            _client.Send(data);
        }

        private void btnClear_Click(object sender, EventArgs e)
        { 
            txtInfo.Text = "";
        }
    }
}
